/*
 * This class will handle request in getting User information from Server
 * All the information would be wrapped in User Class object
 */
package com.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.configuration.Configuration;
import com.object.Meal;
import com.object.User;
import com.user.JSONParser;

public class UserFetch {

	//URL for fetching data
    private static String fetchUserByIdURL = "http://128.199.214.245/android/UserFetch/fetch_user_by_id.php";
    private static String fetchUserByTelephoneURL = "http://128.199.214.245/android/UserFetch/fetch_user_by_telephone.php";
    private static String fetchUserFollowingByIdURL = "http://128.199.214.245/android/UserFetch/fetch_user_following_by_id.php";
    

    //Keys for the Json field
    /*
     * KEY_STATUS shows the status of the request
     * 0 : Fail to get user
     * 1 : Successfully in getting user
     */
    private String KEY_STATUS = "STATUS";
    private String KEY_ID = "ID";
    private String KEY_NAME = "NAME";
    private String KEY_DESCRIPTION = "DESCRIPTION";
    private String KEY_PROFILE_PICTURE = "PROFILE_PICTURE";
    
    private String KEY_NUMBER = "NUMBER";		//Returned by server telling how many users
    
    private String FAIL = "0";
    private String SUCCESS = "1";
    
    //For making httpRequest
    private JSONParser jsonParser;
    private JSONObject result;
    List<NameValuePair> params;
    
    
    //Constructor
    public UserFetch(){
        jsonParser = new JSONParser();
    }
    
    /*
	 * fetchUserById function will return an User object based on user id entered
	 * - non-null	: Data of the user with id = id
	 * - null		: No such user
	 */
	public User fetchUserById(int id){
		//Get Json object
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchUserByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the user
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserById - User found");
					}
					
					// Store information to object
					String name = result.getString(KEY_NAME);
					String description = result.getString(KEY_DESCRIPTION);
					String profile_picture = result.getString(KEY_PROFILE_PICTURE);
					
					User user = new User(id,name,description,profile_picture);
					
					return user;
					
				}else{
					//Fail to find such user
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserById - Unable to find user");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("UserFetch","fetchUserById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("UserFetch","fetchUserById - Exception");
			}
		}

		return null;
	}
	
	
	public User fetchUserByTelephone(String Telephone){
		//Get Json object
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("telephone",Telephone));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchUserByTelephoneURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the user
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserByTelephone - User found");
					}
					
					// Store information to object
					int id = Integer.parseInt(result.getString(KEY_ID));
					String name = result.getString(KEY_NAME);
					String description = result.getString(KEY_DESCRIPTION);
					String profile_picture = result.getString(KEY_PROFILE_PICTURE);
					
					User user = new User(id,name,description,profile_picture);
					
					return user;
					
				}else{
					//Fail to find such user
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserByTelephone - Unable to find user");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("UserFetch","fetchUserByTelephone - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("UserFetch","fetchUserByTelephone - Exception");
			}
		}

		return null;
	}
	
	public String fetchUserNameById(int id){
		//Get Json object
		// Building Parameters
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id",Integer.toString(id)));
		        
		//Start a new thread and use POST method to send telephone and passcode to authURL
		//Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchUserByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
				
		while(attemptThread.isAlive()){
			//Wait for server response
		}
				
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserNameById - User found");
					}
					
					// Return the name of the restaurant
					return result.getString(KEY_NAME);
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserNameById - Unable to find user");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("UserFetch","fetchUserNameByID - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("UserFetch","fetchUserNameById - Exception");
			}
		}
			return null;
	}
	
	/*
	 * This function will return a list of users followed by the input user
	 * WARNING : Test function has not been tested
	 */
	public List<User> fetchUserFollowingById(int user){
		// Building Parameters
       params = new ArrayList<NameValuePair>();
       //No parameter
       params.add(new BasicNameValuePair("user",Integer.toString(user)));
       
       //Start a new thread and use POST method to send telephone and passcode to authURL
       //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchUserFollowingByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Meal
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserFollowingById - User found");
					}
					
					int numberOfUser = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <User> userList = new ArrayList<User>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray nameArray 			= result.getJSONArray(KEY_NAME);
					JSONArray descriptionArray 		= result.getJSONArray(KEY_DESCRIPTION);
					JSONArray profilePictureArray 	= result.getJSONArray(KEY_PROFILE_PICTURE);
					
					for(int i=0;i<numberOfUser;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						String name 			= nameArray.getString(i);
						String description 		= descriptionArray.getString(i);
						String profilePicture 			= profilePictureArray.getString(i);
						
						User tmp_user = new User(id,name,description,profilePicture);
						userList.add(tmp_user);
						
					}
					
					return userList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("UserFetch","fetchUserFollowingById - Unable to find user");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("UserFetch","fetchUserFollowingById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("UserFetch","fetchUserFollowingById - Exception");
			}
		}
		return null;
	}
}
